const { User, Resource } = require('../models');
const cozeClient = require('../utils/cozeClient');

/**
 * 生成教学图像
 * @route POST /api/media/image
 */
const generateImage = async (req, res, next) => {
  try {
    const { knowledgeDesc, style, userId = 1 } = req.body;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 构建Coze智能体输入参数
    const cozeParams = {
      knowledgeDesc,
      style: style || user.stylePreference?.imageStyle || '写实',
      resolution: '1024x1024', // 默认分辨率
      format: 'png' // 默认格式
    };
    
    // 3. 调用Coze智能体生成图像
    const imageResult = await cozeClient.callBot('imageBot', cozeParams);
    
    // 4. 保存到资源表
    const resource = await Resource.create({
      userId,
      type: 'image',
      content: {
        imageUrl: imageResult.imageUrl,
        prompt: knowledgeDesc,
        style,
        generatedAt: new Date().toISOString()
      },
      isSaved: true // 默认保存到资源库
    });
    
    // 5. 更新用户风格偏好
    if (style && (!user.stylePreference || user.stylePreference.imageStyle !== style)) {
      const stylePreference = user.stylePreference || {};
      stylePreference.imageStyle = style;
      await user.update({ stylePreference });
    }
    
    // 6. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        imageUrl: imageResult.imageUrl,
        resourceId: resource.id,
        status: "已同步至资源库"
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 生成教学视频
 * @route POST /api/media/video
 */
const generateVideo = async (req, res, next) => {
  try {
    const { script, duration, animationStyle, userId = 1 } = req.body;
    
    // 1. 获取用户信息
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '用户不存在'
      });
    }
    
    // 2. 先调用脚本优化智能体润色脚本
    const scriptOptimizeParams = {
      script,
      duration: `${duration}秒`,
      purpose: '教学视频'
    };
    
    const optimizedScriptResult = await cozeClient.callBot('scriptOptimizeBot', scriptOptimizeParams);
    const optimizedScript = optimizedScriptResult.optimizedScript || script;
    
    // 3. 构建视频生成智能体输入参数
    const videoParams = {
      script: optimizedScript,
      duration: `${duration}秒`,
      animationStyle: animationStyle || user.stylePreference?.videoStyle || '2D动画',
      withSubtitle: true
    };
    
    // 4. 调用Coze智能体生成视频
    const videoResult = await cozeClient.callBot('videoBot', videoParams);
    
    // 5. 保存到资源表
    const resource = await Resource.create({
      userId,
      type: 'video',
      content: {
        videoUrl: videoResult.videoUrl,
        subtitleUrl: videoResult.subtitleUrl,
        originalScript: script,
        optimizedScript,
        duration,
        animationStyle,
        generatedAt: new Date().toISOString()
      },
      isSaved: true // 默认保存到资源库
    });
    
    // 6. 更新用户风格偏好
    if (animationStyle && (!user.stylePreference || user.stylePreference.videoStyle !== animationStyle)) {
      const stylePreference = user.stylePreference || {};
      stylePreference.videoStyle = animationStyle;
      await user.update({ stylePreference });
    }
    
    // 7. 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        videoUrl: videoResult.videoUrl,
        subtitleUrl: videoResult.subtitleUrl,
        resourceId: resource.id
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取媒体资源详情
 * @route GET /api/media/:resourceId
 */
const getMediaDetail = async (req, res, next) => {
  try {
    const { resourceId } = req.params;
    
    // 查询资源
    const resource = await Resource.findOne({
      where: {
        id: resourceId,
        type: ['image', 'video'] // 只查询图像或视频类型
      }
    });
    
    if (!resource) {
      return res.status(404).json({
        code: 404,
        success: false,
        message: '媒体资源不存在'
      });
    }
    
    // 返回结果
    res.json({
      code: 200,
      success: true,
      data: {
        resourceId: resource.id,
        userId: resource.userId,
        type: resource.type,
        content: resource.content,
        generateTime: resource.generateTime,
        isSaved: resource.isSaved
      }
    });
  } catch (error) {
    next(error);
  }
};

module.exports = {
  generateImage,
  generateVideo,
  getMediaDetail
};